import Layout from '@/Layout';
import {
  batchDeleteTags,
  createTag,
  deleteTag,
  filtertTagsList,
} from '@/services/tags';
import { Tag } from '@/services/tags/typing';
import {
  ActionType,
  FooterToolbar,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Input, message, Modal, Popconfirm } from 'antd';
import { useRef, useState } from 'react';

const params = {
  current: 1,
  pageSize: 15,
};

const Tags: React.FC = () => {
  const tableRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<Tag[]>([]);
  const [addTagModal, setAddTagModal] = useState({
    visible: false,
    tagName: '',
  });
  const [tagName, setTagName] = useState('');
  function changeTagName(e: React.ChangeEvent<HTMLInputElement>) {
    setTagName(e.target.value);
  }

  const columns: ProColumns<Tag>[] = [
    {
      title: '标签名',
      dataIndex: 'tag_name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填',
          },
        ],
      },
      search: {
        transform: (value) => {
          return {
            keywords: value,
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, tag: Tag) => (
        <Popconfirm
          title="确认删除?"
          onConfirm={async () => {
            const res = await deleteTag(tag.tag_id);
            message.success(res.msg);
            tableRef.current?.reload();
          }}
        >
          <a>删除</a>
        </Popconfirm>
      ),
    },
  ];

  const operateModal = async (isAdd?: boolean) => {
    if (isAdd) {
      if (!tagName) {
        message.error('标签名不能为空');
        return;
      }
      const res = await createTag(tagName.trim());
      message.success(res.msg);
      tableRef.current?.reload();
    }
    setAddTagModal((prev) => ({
      ...prev,
      visible: false,
    }));
    setTagName('');
  };

  return (
    <Layout>
      <ProTable<Tag>
        rowKey="tag_id"
        actionRef={tableRef}
        defaultSize="small"
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setAddTagModal((prev) => ({
                ...prev,
                visible: true,
              }));
            }}
          >
            创建标签
          </Button>,
        ]}
        pagination={{
          pageSize: 15,
          onChange: (page) => (params.current = page),
        }}
        params={params}
        request={async (condition) => {
          const { data } = await filtertTagsList({
            page: condition.current ?? 1,
            pageSize: condition.pageSize ?? 15,
            keywords: condition.keywords,
          });
          return {
            data: data?.list || [],
            success: true,
            total: data.total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              const res = await batchDeleteTags(selectedRowsState);
              message.success(res.msg);
              setSelectedRows([]);
              tableRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <Modal
        title="添加标签"
        closable={false}
        open={addTagModal.visible}
        onOk={() => operateModal(true)}
        onCancel={() => operateModal()}
      >
        <Input placeholder="标签名" value={tagName} onChange={changeTagName} />
      </Modal>
    </Layout>
  );
};

export default Tags;
